package com.web.my12306.controller;

import com.alibaba.fastjson.JSON;
import com.web.my12306.dao.IUserDao;
import com.web.my12306.dao.impl.UserDaoImpl;
import com.web.my12306.pojo.*;
import com.web.my12306.service.UserService;
import com.web.my12306.service.impl.UserServiceImpl;
import com.web.my12306.util.FileUtil;
import com.web.my12306.util.Md5Utils;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;


public class UserServlet extends InnerDispatcherController
{
    private UserService userService = new UserServiceImpl();
    private static final String RESPONSE_START = "<!DOCTYPE html><html><head><title></title></head><body><script type='text/javascript'>";

    private static final String RESPONSE_ENDED = "</script></body></html>";
    /**
     * @author 金刚天使葫芦娃
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    /**
     * @author 金刚天使葫芦娃 用户登录、验证码、用户修改密码，退出登录
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    //用户登录
    public void Login(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");


        User user = new User();
        //从表单获取数据
        user.setLoginname(request.getParameter("loginname"));
        user.setPassword(request.getParameter("password"));
        user.setCode(request.getParameter("codein"));

        //登录判断
        if (user != null){
            HttpSession session=request.getSession();
            String code=(String)session.getAttribute("code");
            if (!code.equalsIgnoreCase(user.getCode())){
                String msg="验证码不正确";
                request.setAttribute("msg",msg);
                response.sendRedirect(request.getContextPath()+"/userLogin.jsp");
            }else {
                //调用Login方法查询数据库
                IUserDao iUserDao = new UserDaoImpl();
                User u = iUserDao.login(user.getLoginname(),Md5Utils.md5(user.getPassword()));

                if (u==null){
                    String msg="用户名或密码不正确！请重新输入！";
                    request.setAttribute("msg",msg);
                    response.sendRedirect(request.getContextPath()+"/userLogin.jsp");
                }else {
                    //request.getRequestDispatcher("/index.jsp").forward(request,response);//登陆成功
                    HttpSession session1=request.getSession();
                    session1.setAttribute("user",u);
                    session.setAttribute("uid",u.getUid());
                    response.sendRedirect(request.getContextPath()+"/userIndex.jsp");
                }
            }
        }else {
            String msg="用户名或密码不正确！请重新输入！";
            request.setAttribute("msg",msg);
            response.sendRedirect(request.getContextPath()+"/userLogin.jsp");
        }

    }
    //验证码
    /**
     * 金刚天使葫芦娃
     */
    private static final long serialVersionUID = 1L;

    private char code[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
            'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
            'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M',
            'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '2',
            '3', '4', '5', '6', '7', '8', '9' };
    private static final int WIDTH = 50;
    private static final int HEIGHT = 20;
    private static final int LENGTH = 4;
    public void ValidateCode(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 设置响应报头信息
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        // 设置响应的MIME类型
        response.setContentType("image/jpeg");

        BufferedImage image=new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
        Font mFont=new Font("arival",Font.TRUETYPE_FONT,18);
        Graphics g = image.getGraphics();
        Random rd=new Random();

        //设置背景颜色
        g.setColor(new Color(rd.nextInt(55) + 200, rd.nextInt(55) + 200, rd
                .nextInt(55) + 200));
        g.fillRect(0, 0, WIDTH, HEIGHT);
        // 设置字体
        g.setFont(mFont);

        // 画边框
        g.setColor(Color.black);
        g.drawRect(0, 0, WIDTH - 1, HEIGHT - 1);
        // 随机产生的验证码
        String result = "";
        for (int i = 0; i < LENGTH; ++i) {
            result += code[rd.nextInt(code.length)];
        }
        HttpSession session=request.getSession();
        session.setAttribute("code",result);
        // 画验证码
        for (int i = 0; i < result.length(); i++) {
            g.setColor(new Color(rd.nextInt(200), rd.nextInt(200), rd
                    .nextInt(200)));
            g.drawString(result.charAt(i) + "", 12 * i + 1, 16);
        }
        // 随机产生2个干扰线
        for (int i = 0; i < 2; i++) {
            g.setColor(new Color(rd.nextInt(200), rd.nextInt(200), rd
                    .nextInt(200)));
            int x1 = rd.nextInt(WIDTH);
            int x2 = rd.nextInt(WIDTH);
            int y1 = rd.nextInt(HEIGHT);
            int y2 = rd.nextInt(HEIGHT);
            g.drawLine(x1, y1, x2, y2);
        }
        // 释放图形资源
        g.dispose();
        try {
            OutputStream os=response.getOutputStream();

            // 输出图像到页面
            ImageIO.write(image,"JPEG",os);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    /**
     *方艺
     *2017.9.12
     */
    public void addUser(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        User user = new User();
        //从页面获取数据
        user.setLoginname(request.getParameter("loginname"));
        //  user.setPassword(request.getParameter("password"));
        user.setPassword(Md5Utils.md5(request.getParameter("password")));
        user.setImg(request.getParameter("icon"));
        user.setName(request.getParameter("realname"));
        user.setSex(request.getParameter("sex"));
        user.setProv(request.getParameter("prov"));
        user.setCity(request.getParameter("city"));
        user.setCardtype(request.getParameter("cardtype"));
        user.setCardid(request.getParameter("cardid"));
        user.setTel(request.getParameter("tel"));
        user.setUtype(request.getParameter("utype"));
        user.setBeizhu(request.getParameter("beizhu"));
        user.setState(1);


        userService.add(user);

        response.sendRedirect(request.getContextPath()+"/userLogin.jsp");
        System.out.println("111");

    }
    public void addIcon(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {String classPath = Thread.currentThread().getContextClassLoader().getResource("/").getPath();

        // 利用相对路径算出 存储头像的路径
        classPath += "../../" + CommonConstants.ICON_FOLDER;
//        System.out.println(classPath);///D:/SVN/My12306/target/maventest/WEB-INF/classes/../../icons/

        String filePath = Thread.currentThread().getContextClassLoader().getResource("/").getPath();
        filePath += "../../../../src/main/webapp/" +CommonConstants.ICON_FOLDER;

        // 获取当前的时间戳
        long time = (new Date()).getTime();

        // 结合以上数据为基础计算出一个新的文件路径用于存储图片本身
        File target = new File(classPath + File.separator + time + ".jpg");

        // 将路径归一
        target = target.getCanonicalFile();

        // 确保目标文件所在目录都存在
        target.getParentFile().mkdirs();

        // 从请求获取数据流
        ServletInputStream in = request.getInputStream();

        // 新建图片的存储输出流
        FileOutputStream fileOutputStream =new FileOutputStream(target);

        // 从请求对象读取出报文字节数组
        byte[] dataBody = FileUtil.readBody(request);
        // 以 ISO-8859-1 编码方式转换成字符串
        String textBody = new String(dataBody, "ISO-8859-1");
        // 计算出图片数据在字节数组中的偏移量
        FileUtil.Position p = FileUtil.getFilePosition(request, textBody);
        // 结合输出流，报文字节数组，读取偏移量 将图片保存至硬盘
        FileUtil.writeTo(fileOutputStream, dataBody, p);
////保存硬盘
//        // 结合以上数据为基础计算出一个新的文件路径用于存储图片本身
//        File target2 = new File(filePath + File.separator + time + ".jpg");
//        // 将路径归一
//        target2 = target.getCanonicalFile();
//        // 确保目标文件所在目录都存在
//        target2.getParentFile().mkdirs();
//        // 新建图片的存储输出流
//        FileOutputStream fileOutputStream2 =new FileOutputStream(target2);
//        // 结合输出流，报文字节数组，读取偏移量 将图片保存至硬盘
//        FileUtil.writeTo(fileOutputStream2, dataBody, p);



        // 新建一个文件上传响应消息对象，其中包含图片在网站中的相对路径
        UploadIconResponse uiresponse = new UploadIconResponse();
        uiresponse.setUrl(CommonConstants.ICON_FOLDER + time + ".jpg");

        // 设定响应消息的 MIME 为 纯文本，要求浏览器不出处理，然后输出 JSON 字符串
        response.setContentType("text/html");
        response.getWriter().append(RESPONSE_START).append("var response = ").append(JSON.toJSONString(uiresponse)).append(RESPONSE_ENDED);
    }

    public void queryAll(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        List<User> userList=userService.queryALl();
        int page = 0;
        int rows = 0;
        try
        {
            page = Integer.valueOf(request.getParameter("page"));
            rows = Integer.valueOf(request.getParameter("rows"));
        } catch (NumberFormatException e)
        {
            e.printStackTrace();
        }


        int start = (page - 1) * rows;//page从1开始的，减一，开始数据index
        //并没有太大优势的sql分页查询，因为反正要查总数，
                List<User> pageList=new ArrayList<>();
                for (int i = start; i < start + rows&&i<userList.size(); i++) {
                    pageList.add(userList.get(i));
                }

        EasyUIDataGridJSON responseObject = new EasyUIDataGridJSON();
        responseObject.setTotal(userList.size());//数据总数，方便显示有多少页，限制页面超出
        responseObject.setRows(pageList);//页面显示数据的list

        response.setContentType("application/json");
        response.getWriter().append(JSON.toJSONString(responseObject));

    }
    //修改密码
    public void editPassword(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        IUserDao iUserDao=new UserDaoImpl();

        //获取登录名
        HttpSession session=request.getSession();
        User user=(User)session.getAttribute("user");
        //获取数据库中密码
        User old=iUserDao.findByLoginname(user.getLoginname());
        System.out.println("数据库中原密码"+old.getPassword());

        //获取新密码
        String oldPassword = request.getParameter("oldPassword");
        String txtNewPass = request.getParameter("txtNewPass");
        //        System.out.println("表单中的原密码"+oldPassword);
        //        System.out.println("表单中的新密码"+txtNewPass);

        //判断原密码是否正确
        if (old.getPassword().equals(Md5Utils.md5(oldPassword))){
            iUserDao.editPassword(user.getLoginname(),Md5Utils.md5(txtNewPass));
            //            System.out.println("姓名"+user.getLoginname()+"新密码"+Md5Utils.md5(user.getPassword()));
            //更新session中的user对象
            user.setPassword(Md5Utils.md5(txtNewPass));
            //            System.out.println("session中的密码"+Md5Utils.md5(user.getPassword()));
            //返回data
            PrintWriter out=response.getWriter();
            out.print("1");
        }else {
            PrintWriter out=response.getWriter();
            System.out.println("跳到else");
            out.print("2");
        }

    }
    //退出登录
    public void exitLogin(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        HttpSession session=request.getSession(true);
        session.invalidate();
        response.sendRedirect(request.getContextPath()+"/userLogin.jsp");
    }

}
